package com.boot.unity.api.wx.service;

import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.wx.utils.AdmissionCardUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class ZsWxImageService {

    @Value("${wx.miniapp.appid}")
    private String appid;

    @Value("${wx.miniapp.secret}")
    private String appsecret;

    @Value("${img.filePath}")
    private String filePath;


    @Value("${img.url}")
    private String url;

    @Value("${img.urlNoHttp}")
    private String urlNoHttp;

    @Value("${img.httpval}")
    private String httpval;

    private AdmissionCardUtil admissionCardUtil = AdmissionCardUtil.getInstance();

    public void createJPGManagerHb(JSONObject json){
        // 进行图片服务器上传处理
        String managerId = json.getString("id");
//        String idcard = json.getString("idcard");
        String role = json.getString("perm_role");
        String filename = managerId +".png";

        String allPath = filePath+"images//"+filename;// 获取访问的路径
        System.out.println("小程序码访问路径：：：："+allPath);
        String baseImg = "";
        try {
            InputStream is = new FileInputStream(new File(allPath));
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            baseImg = Base64.getEncoder().encodeToString(bytes);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /************************将图片进行保存，并发送*******************************/
        // 生成招生海报图片
        String jpgPath = filePath+"images//" + managerId + "hb.jpg";
        String pdfPath = filePath+"admission.pdf";
        Map<String,String> map = new HashMap<>();
//            map.clear();
        map.put("id", managerId);
        map.put("school", json.getString("school_name"));
        map.put("phone", json.getString("phone"));
        map.put("referrer", json.getString("name"));
        map.put("imgPath", allPath);
        map.put("jpgPath", jpgPath);
        map.put("pdfPath", pdfPath);
        map.put("filePath", filePath);
        try {
            admissionCardUtil.createJpg(map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    //生成招生二维码的小程序图片
    public void createWxQrCodeFile(String scene){
        System.out.println("-----------------------进行生成小程序招生码进行处理招生业务-----------------------");
        // 获取token
        String token = getAccess_token(appid, appsecret);
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("page", "pages/web/qrzs/index");
            paramJson.put("scene", scene);
            paramJson.put("width", 200);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            System.out.println("小路径："+filePath+"images//" +scene+".png");
            OutputStream os = new FileOutputStream(new File(filePath+"images//" +scene+".png"));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }




    //获取token的接口地址
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?" + "grant_type=client_credential&appid=APPID&secret=APPSECRET";
    /**
     * 获取access_token
     *
     * @param appid
     * @param appsecret
     * @return
     */
    private static String getAccess_token(String appid, String appsecret) {
        try {
            String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
            JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            return "errer";
        }
    }

    /**
     *
     * @Title: httpsRequest
     * @Description: 发送请求,返回JSONObject对象
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     * @throws Exception
     */
    private static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        JSONObject jsonObject = null;
        try {
            // 使用自定义的信任管理器
            TrustManager[] tm = { new X509TrustManager() {
                /**
                 * 检查客户端证书
                 */
                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                /**
                 * 检查服务器端证书
                 */
                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                /**
                 * 返回受信任的X509证书数组
                 */
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            } };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            // 建立连接
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置请求方式
            conn.setRequestMethod(requestMethod);
            // 当outputStr不为null时,向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 获取输入流
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            // 读取响应内容
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
//            jsonObject = JSONObject.fromObject(buffer.toString());
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception e) {
            throw new Exception("请求/解析失败");
        }
        return jsonObject;
    }


}
